import collections
class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def upsideDownBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if not root:
            return None
        stack = collections.deque()
        node = root
        while node:
            stack.append(node)
            node = node.left
        root = stack.pop()
        prev = root
        while stack:
            next = stack.pop()
            prev.left = next.right
            prev.right = next
            prev = next
            prev.left = None
            prev.right = None
        return root


